﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.Core.HttpHandlers;
using System.Web.Routing;
using MvcEngine.Core.Repositories;

using MvcEngine.Core;
using System.IO;
using System.Web;
using MvcEngine.Core.Extensions;
using MvcEngine.Core.Content;
using MvcEngine.Core.Helpers;
using MvcEngine.Blog.Managers;

namespace MvcEngine.Blog.Components.Services
{
    public class BlogFileResolver : IFileResolver
    {
        public string GetFilePath(RouteData routeData)
        {
            Control control = ContentManager.Current.GetControlByKey(routeData.GetRequiredString("controlKey"));

            if (control == null)
            {
                LogHelper.Current.WriteError("Control is not found: " + routeData.GetRequiredString("controlKey"));
            }

            Module module = ContentManager.Current.GetModule(control.ModuleId);
            Guard.ThrowIfNull(module);

            if (module == null)
            {
                LogHelper.Current.WriteError("Module is not found: " + control.ModuleId);
            }

            var page = ContentManager.Current.GetPage(routeData.GetRequiredString("pageName"));
            var blog = BlogManager.Current.GetBlogByPage(page.Id);

            string filePath = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Path.Combine(Path.Combine(Path.Combine(
                HttpContext.Current.Request.PhysicalApplicationPath, "Modules"), module.Name), "Content"),
                blog.Id.ToString()), routeData.GetRequiredString("year")), routeData.GetRequiredString("month")), routeData.GetRequiredString("fileName").UrlDecode());

            return filePath;
        }
    }
}
